import { ImportDeclaration, ModuleDeclaration, Project } from "ts-morph";
import { handleModule } from "./handler";
export async function saveTypeScriptDefineFile(pbtsFilePath: string) {
    const project = new Project();
    project.addSourceFileAtPath(pbtsFilePath);
    const file = project.getSourceFileOrThrow(pbtsFilePath);
    const modules = file.getModules();
    // 去掉生成的import
    file.getImportDeclarations().forEach(i => i.remove());
  
    // 对于importString的处理
    file.getImportStringLiterals().forEach(i => {
      const p = i.getParent()?.getParent() as ImportDeclaration;
      p.remove();
    });
  
    handleModule(modules, module => {
      // 去掉生成的class
      const classes = module.getClasses();
      classes.forEach(c => c.remove());
  
      // 去掉生成的rpc-type
      const typeAliases = module.getTypeAliases();
      typeAliases.forEach(t => t.remove());
        module.getInterfaces().forEach(item => {
          // 获取语法树
          const structure = item.getStructure();
          structure.properties?.forEach(property => {
            property.hasQuestionToken = false;
            if (typeof property.type === 'string') {
              property.type = property.type.replace(/^\((\S*)\|null\)$/, '$1');
            }
          });
          item.set(structure);
        });
    });
    project.saveSync();
  }
  
